// 管理账号信息

var path_url = '';
var path_url_img = '';
let orgid ="440004904";
// const baseUrl = 'https://lianjiang.nxk520.com'; // 接口地址
// const wsUrl = 'wss://lianjiang.nxk520.com/websocket'  // webSocket接口地址
const baseUrl = 'https://www.daylaiyy.com'; // 接口地址
const wsUrl = 'wss://www.daylaiyy.com/websocket'  // webSocket接口地址
const consultationWsUrl = 'wss://www.daylaiyy.com/consultation'  // 会诊webSocket接口地址
const userTmplIds = ['-KuOR8-Z1F3XYobkCswQC0a8Dr6-5RxN6EOTbZ1jyFs'] // 用户服务模版消息id
const doctorTmplIds = ['ptjCNvuRduZ9b1F4oXDy2ycP0V8D-wtrzF7RB3heaVU'] // 医生服务模版消息id
const isHis = false ; // 是否显示廉江his内容
const isEsgin = true; // 是否需要使用ca
const hospitalType = 'cddyl'
const TRTCTYPE = 'agora' // 使用的视频商家 Tencent / agora

// 视屏appid
// wx279a3fd5ae886fba
// 一线appid
// wxe1adb881c11da365

/**
 * 将用户数据存储到LocalStorage中
 * @param userJson
 */
const setUserLocalStorage = function (userJson) {
  wx.setStorageSync("userJson", userJson);
}
/**
 * 清除userjson 数据
 * @return json
 */
const delUserLocalStorage = function () {
  wx.setStorageSync("userJson", '');
}


/**
 * 从cookie中得到一条userjson 数据
 * @return json
 */
const getUserLocalStorage = function () {
  var userJson = wx.getStorageSync("userJson");
  if (isUndefinedAndEmpty(userJson)) {
    return '{}';
  }
  return strToJson(userJson);
}


//字符串转Int
const strToInt = function (str) {
  if (isNaN(str) || isUndefinedAndEmpty(str)) {
    return 0;
  }
  return parseInt(str);
}

// 是否为空
const isUndefinedAndEmpty = function (obj) {
  obj = (obj + "").replace(/^\s+|\s+$/g, "");


  if (undefined == obj || "undefined" == obj || "" == obj || null == obj || "null" == obj || "{}" == obj || {} == obj) {
    return true;
  }
  return false;
}
//保留3位小数
var filters = {
      toFix: function (value) {
          return value.toFixed(2) // 此处3为保留两位小数，保留几位小数
      }
}

/**
 * 判断当前用户是否已经登录
 * @return json
 */
const isLogin = function () {
  var userJson = wx.getStorageSync("userJson");
  if (isUndefinedAndEmpty(userJson) || userJson == "{}") {
    return false;
  }
  return true;
}

/**
 * 旧请求方法
 * @param {*} jsonAjax 接口名
 * @param {*} backmethod 回掉函数
 */
const getAjaxData = function (jsonAjax, backmethod) {
    let params = {
      "rand": Math.random(),
      "uid": JSON.parse(wx.getStorageSync('userInfo')).id,
      "utype":1,
      "orgid":orgid
    }
    for (let key in jsonAjax.jsonData) {
      params[key] = jsonAjax.jsonData[key]
    }
    wx.request({
      url: cflzUrl + jsonAjax.url,
      method: 'POST',
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      }, //自定义请求头信息
      dataType: "html",
      complete: (res) => {
          backmethod(JSON.parse(res.data));
      }
    });
}


/**
 * 将一个字符串转化为一个json对象 传入一个json格式数据
 *
 * @param jsonStr
 * @return JSON
 */

const strToJson = function (jsonStr) {
  return JSON.parse(jsonStr);
}
/**
 * 将一个json对象数据转化为一个字符串数据 传一个json对象
 *
 * @param jsonObj
 * @return Str
 */
const jsonToStr = function (jsonObj) {
  return JSON.stringify(jsonObj);
}
// 图片路径处理
const getUserImgPub = function (user_img, srcimg) {
  if (isUndefinedAndEmpty(user_img)) {
    if (isUndefinedAndEmpty(srcimg)) {
      user_img = '/static/images/head.png';
    } else {
      user_img = srcimg;
    }

  } else if (user_img.indexOf('http') == -1) { //微信头像
    user_img = path_url_img + user_img;
  }
  return user_img;
}
// 弹框提示
const showToast = function (obj) {
  wx.showToast({
    icon: "none",
    title: obj,
    duration: 2000
  })
}

/**
 * 正则验证规则
 * @param type
 * @param value
 */
const validateElement = function (type, value) {
  var $pintu = value.replace(/(^\s*)|(\s*$)/g, "");
  switch (type) {
    case "required":
      return /[^(^\s*)|(\s*$)]/.test($pintu);
      break;
    case "chinese":
      return /^[\u0391-\uFFE5]+$/.test($pintu);
      break;
    case "number":
      return /^\d+$/.test($pintu);
      break;
    case "integer":
      return /^[-\+]?\d+$/.test($pintu);
      break;
    case "plusinteger":
      return /^[+]?\d+$/.test($pintu);
      break;
    case "double":
      return /^[-\+]?\d+(\.\d+)?$/.test($pintu);
      break;
    case "plusdouble":
      return /^[+]?\d+(\.\d+)?$/.test($pintu);
      break;
    case "english":
      return /^[A-Za-z]+$/.test($pintu);
      break;
    case "password":
      return /^([a-z0-9\w\!\#\$\%\^\&\*\.\~]|[a-zA-Z0-9\w\!\#\$\%\^\&\*\.\~]){5,16}$/.test($pintu);
      break;
    case "username":
      return /^[a-z]\w{5,}$/i.test($pintu);
      break;
    case "mobile":
      return /^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}?$|15[0-9]\d{8}?$|16[0-9]\d{8}?$|17[0-9]\d{8}?$|18[0-9]\d{8}?$|19[0-9]\d{8}?$|147\d{8}?$/.test($pintu);
      break;
    case "phone":
      return /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/.test($pintu);
      break;
    case "tel":
      return /^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}?$|15[89]\d{8}?$|170\d{8}?$|18[0-9]\d{8}?$|147\d{8}?$/.test($pintu) || /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/.test($pintu);
      break;
    case "email":
      return /^[^@]+@[^@]+\.[^@]+$/.test($pintu);
      break;
    case "url":
      return /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/.test($pintu);
      break;
    case "ip":
      return /^[\d\.]{7,15}$/.test($pintu);
      break;
    case "qq":
      return /^[1-9]\d{4,10}$/.test($pintu);
      break;
    case "currency":
      return /^\d+(\.\d+)?$/.test($pintu);
      break;
    case "zip":
      return /^[1-9]\d{5}$/.test($pintu);
      break;
      /**自定义验证  excel的后缀***/
    case "xlsx":
      return /^.*?\.(xlsx|xls)$/.test($pintu);
      break;
      /**自定义验证  img的后缀***/
    case "img":
      return /^.*?\.(bmp|jpeg|jpg|gif|png)$/.test($pintu);
      break;
      /**自定义验证  压缩文件的后缀***/
    case "yaSuo":
      return /^.*?\.(rar|zip|7z|gz|bz|ace|uha|uda|zpaq)$/.test($pintu);
      break;
      /**自定义验证  邮箱或 手机***/
    case "mobile_or_email":
      return (/^[^@]+@[^@]+\.[^@]+$/.test($pintu)) || (/^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}?$|15[89]\d{8}?$|170\d{8}?$|147\d{8}?$/.test($pintu) || /^[a-z]\w{2,}$/i.test($pintu));
      break;
      /**自定义验证  身份证***/
    case "idCard":
      return /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/.test($pintu);
      break;
  }
}

/**
 * 判断是否登录
 *
 * @param jsonObj
 * @return Str
 */
const login_istrue = function (jsonObj) {
  if (wx.getStorageSync("user_idset") == '') {
    return 1;
  } else {
    return 2;
  }
}
const loginuserid = function (jsonObj) {
  wx.showModal({
    title: '温馨提示',
    content: '此功能要先登录账号，请前往登录',
    success(res) {
      if (res.confirm) {
        wx.navigateTo({
          url: '/pages/login/login'
        })
      }
    }
  })
}
//获取当前日期
const timeNew = function () {
  var str = new Date().getTime();
  var oDate = new Date(str),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth() + 1,
    oDay = oDate.getDate(),
    oHour = oDate.getHours(),
    oMin = oDate.getMinutes(),
    oSen = oDate.getSeconds(),
    oTime2 = oYear + '-' + addZero(oMonth) + '-' + addZero(oDay);
  return oTime2;
}
const addZero = function (num) {
  if (parseInt(num) < 10) {
    num = '0' + num;
  }
  return num;
}
//年月日 20191119
const nothinglrsj = function (str) {
  var str_Y = str.substring(0, 4);
  var str_M = str.substring(5, 7);
  var str_D = str.substring(8, 10);
  return str_Y + str_M + str_D;

}
//年月日 2019年11月19日
const nothinglrsj2 = function (str) {
  var str_Y = str.substring(0, 4);
  var str_M = str.substring(5, 7);
  var str_D = str.substring(8, 10);
  return str_Y + '年' + str_M + '月' + str_D + '日';

}
//判断是否为空
const nothingFun = function (str, txt) {
  if (isUndefinedAndEmpty(str)) {
    if (isUndefinedAndEmpty(txt)) {
      txt = '';
    }
    return txt
  } else {
    return str
  }
}
//打开页面
const openPage = function (Url) {
  wx.navigateTo({
    url: Url
  })
}
/**
 * 将一个字符串转化成float
 * @param str 需要转换的字符串
 */
const strToFloat = function (str) {
  if (isNaN(str)) {
    return 0;
  }
  return parseFloat(str);
}


/**
 * 存储 sessionStorage
 */
const setStore = (name, content) => {
  if (!name) return;
  if (typeof content != 'string') {
      content = JSON.stringify(content);
  }

  wx.setStorageSync(name, content);
}

/**
* 获取 sessionStorage
*/
const getStore = name => {
  if (!name) return;
  return wx.getStorageSync(name);
}

// 返回前number天的日期格式为2020-02-02，参数number为前几天
const getBeforeDate = (number) =>  {
  const num = number;
  const date = new Date();
  let year = date.getFullYear();
  let mon = date.getMonth() + 1;
  let day = date.getDate();
  if (day <= num) {
      if (mon > 1) {
          mon = mon - 1;
      } else {
          year = year - 1;
          mon = 12;
      }
  }
  date.setDate(date.getDate() - num);
  year = date.getFullYear();
  mon = date.getMonth() + 1;
  day = date.getDate();
  const s = year + '-' + (mon < 10 ? ('0' + mon) : mon) + '-' + (day < 10 ? ('0' + day) : day);
  return s;
}
/**
* 删除 sessionStorage
*/
const removeStore = name => {
  if (!name) return;
  wx.removeStorageSync(name);
}

/**
 * 深拷贝（deepClone）
 * @param {*} obj 拷贝的对象
 * @param {*} hash
 */
const deepClone = ( obj, hash = new WeakMap() ) => {
  // 如果是 null 或者 undefined 我就不进行拷贝操作了
  if(obj === null ) return obj
  if(obj instanceof Date ) return new Date( obj )
  if(obj instanceof RegExp) return new RegExp(obj)
  // obj 可能是对象或者普通值，如果只是个函数的话，也不进行拷贝
  if(typeof obj !== "object") return obj
  // 是对象的话就要进行拷贝了
  if(hash.get(obj)) return hash.get(obj)
  // 找到的是所属类原型上的 constructor，而原型上的 construction 指向的是当前类的本身
  let cloneObj = new obj.constructor()
  hash.set(obj, cloneObj);
  for(let key in obj) {
      if(obj.hasOwnProperty(key)) {
          // 实现一个递归拷贝
          cloneObj[key] = deepClone(obj[key], hash)
      }
  }
  return cloneObj
  }
/**
 *  yy-mm-dd 转 时间戳
 * @param {*} time
 */
const timeFormat = (time) => {
    if(!time) return
    var timestamp2 = time.replace(/-/g, '/')   //为了兼容IOS，
    timestamp2 = Date.parse(timestamp2)
    return timestamp2;
}
/**
 *  yyyy-MM-dd hh:mm:ss转换为时间戳
 * @param {*} time
 */
const dataFormat = (stringTime) => {
  let timestamp = stringTime.replace(/-/g, '/')   //为了兼容IOS，需先将字符串转换为'2018/9/11 9:11:23'
  timestamp = Date.parse(timestamp)    //返回'2018-9-12 9:11:23'的时间戳
  return timestamp;
}
/**
 * 获取当天24的时间戳
 */
const get24Time = () => {
    return new Date(new Date(new Date().toLocaleDateString()).getTime() + 25 * 60 * 60 * 1000 -1).getTime();
}
/**
 * 获取当前日期，日期格式为yyyy-mm-dd HH:MM
 */
const getDate = () => {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
        day = "0" + day;
    }
    if (hours >= 0 && hours <= 9) {
        hours = "0" + hours;
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + day + " " + hours + seperator2 + minutes + seperator2 + seconds;
    return currentdate;
}
/**
 * 判断开发环境
 *  miniProgram.envVersion的合法值：develop开发版、trial体验版、release正式版
 */
const getEnv = () => {
  let accountInfo = wx.getAccountInfoSync();
  let env = accountInfo.miniProgram.envVersion;
  return env
}
/**
 * 播放"叮叮叮"音乐
 */
//播放声音
const audioMsgPlay = () => {
  const audioMsg = wx.createInnerAudioContext();
  audioMsg.src = 'https://yixiang-hospital.oss-cn-shenzhen.aliyuncs.com/mini/minImg/dingding.mp3';
  audioMsg.play();
  setTimeout(() => {
    audioMsg.stop();
    audioMsg.destroy();
  }, 1500);
}

/**
 * 随机生成文件名
 */
const randomString = function(len) { // 生成随机字符串
  let myDate = new Date();
  let seconds = myDate.getTime();
  len = len || 32;
  let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789';

  let maxPos = chars.length;
  let pwd = '';
  for (let i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return seconds + pwd;
};


const getSuffix = function(filename) { // 获取文件后缀
  var pos = filename.lastIndexOf('.')
  var suffix = ''
  if (pos != -1) {
      suffix = filename.substring(pos)
  }
  return suffix;
};
const randomFilename = function(filename) {
  var suffix = getSuffix(filename);
  var random_filename = randomString(10) + suffix;
  return random_filename;
};


export default {
  getAjaxData,
  path_url,
  path_url_img,
  orgid,
  strToJson,
  jsonToStr,
  getUserLocalStorage,
  setUserLocalStorage,
  delUserLocalStorage,
  isLogin,
  isUndefinedAndEmpty,
  validateElement,
  getUserImgPub,
  showToast,
  strToInt,
  loginuserid,
  login_istrue,
  timeNew,
  addZero,
  nothinglrsj,
  nothinglrsj2,
  nothingFun,
  openPage,
  strToFloat,
  setStore,
  getStore,
  removeStore,
  deepClone,
  baseUrl,
  timeFormat,
  dataFormat,
  wsUrl,
  consultationWsUrl,
  get24Time,
  getDate,
  getEnv,
  audioMsgPlay,
  userTmplIds,
  doctorTmplIds,
  filters,
  randomString,
  randomFilename,
  hospitalType,
  isHis,
  getBeforeDate,
  isEsgin,
  TRTCTYPE
}
